package com.baseweb.webadmin.controller.admin;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.RoleType;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByChannelKeyWordBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.MD5Util;
import com.baseweb.webadmin.core.util.RandCharUtil;
import com.baseweb.webadmin.core.util.UploadUtil;
import com.baseweb.webadmin.service.ContentService;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/content")
public class ContentController extends BaseController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserService userService;

    private String PREFIX = "/content/";

    @RequestMapping(value = "/feedbackManage")
    public String feedbackManage() {
        return PREFIX + "feedbackManage";
    }

    @RequestMapping(value = "/getFeedbackList")
    public void getFeedbackList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                 Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserFeedback> list = contentService.selectFeedbackListByPage(user.getId(), (page-1)*pageSize, pageSize);
        int total = contentService.selectFeedbackListCount(user.getId());
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }


    //等级设置
    @RequestMapping(value = "/addLevelView")
    public String addLevelView(@RequestParam(value = "id",required = false) Integer id,
                                  Model model) {

        model.addAttribute("levelTypeList", LevelType.getAllData());

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        return PREFIX + "addLevelView";
    }

    @RequestMapping(value = "/editLevelView")
    public String editLevelView(@RequestParam(value = "id",required = false) Integer id,
                                   Model model) {

        model.addAttribute("levelTypeList", LevelType.getAllData());

        if (id != null && id > 0){
            model.addAttribute("level", contentService.findLevel(id));
        }

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        return PREFIX + "editLevelView";
    }

    @RequestMapping(value = "/submitLevel")
    public String submitOpenCity(@RequestParam(value = "id",required = false) Integer id,
                                 @RequestParam(value = "start_value",required = false) Integer start_value,
                                 @RequestParam(value = "end_value",required = false) Integer end_value,
                                 @RequestParam(value = "file",required = false) MultipartFile file,
                                 @RequestParam(value = "level_type",required = false) Integer level_type,
                                 @RequestParam(value = "level_icon",required = false) String level_icon,
                                 @RequestParam(value = "level_name",required = false) String level_name,
                                 Model model) {
        try{
            ByLevel byLevel = null;
            if (id != null && id > 0){
                byLevel = contentService.findLevel(id);
            }else{
                byLevel = new ByLevel();
            }

//            User user = getCurrentUser();
            byLevel.setStartValue(start_value);
            byLevel.setEndValue(end_value);
            byLevel.setLevelType(level_type);
            byLevel.setLevelIcon(level_icon);
            byLevel.setLevelName(level_name);
            byLevel.setCreateTime(new DateTime());
            byLevel.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byLevel.setLevelIcon(img_url);
            }

            contentService.insertLevel(byLevel);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "levelManage";
    }

    @RequestMapping(value = "/levelManage")
    public String levelManage() {
        return PREFIX + "levelManage";
    }

    @RequestMapping(value = "/getLevelList")
    public void getLevelList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                 Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByLevel> list = contentService.selectLevelListByPage((page-1)*pageSize, pageSize);
        int total = contentService.selectLevelListCount();
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }


    //数据字典
    @RequestMapping(value = "/dictManage")
    public String dictManage() {
        return PREFIX + "dictManage";
    }

    @RequestMapping(value = "/getDictList")
    public void getDictList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                            @RequestParam(value = "dict_type", required = false) Integer dict_type,
                                 Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByDict> list = contentService.selectDictListByPage(dict_type,(page-1)*pageSize, pageSize);
        int total = contentService.selectDictListCount(dict_type);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }







    @RequestMapping(value = "/channelManage")
    public String channelManage() {
        return PREFIX + "channelManage";
    }

    @RequestMapping(value = "/getChannelList")
    public void getChannelList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                            @RequestParam(value = "id", required = false) Integer id,
                            @RequestParam(value = "position_id", required = false) Integer position_id,
                            @RequestParam(value = "parent_id", required = false) Integer parent_id,
                            Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();

        if (id != null && id > 0){
            ByChannel byChannel = contentService.findChannel(id);
            position_id = byChannel.getPositionId();
            parent_id = byChannel.getId();
        }

        List<ByChannel> list = contentService.selectChannelListByPage(position_id, parent_id, null,(page-1)*pageSize, pageSize);
        int total = contentService.selectChannelListCount(position_id, parent_id, null);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }
    @RequestMapping(value = "/addChannelView")
    public String addChannelView(@RequestParam(value = "id",required = false) Integer id,
                                Model model) {
        model.addAttribute("positionList", ChannelType.getAllChannel());
//        model.addAttribute("parentList", contentService.selectChannelListByPage(null, 0, BaseState.NORMAL.getCode(),1, 50));

        return PREFIX + "addChannelView";
    }

    @RequestMapping(value = "/editChannelView")
    public String editChannelView(@RequestParam(value = "id",required = false) Integer id,
                                 Model model) {
        model.addAttribute("positionList", ChannelType.getAllChannel());
        model.addAttribute("parentList", contentService.selectChannelListByPage(null, 0, BaseState.NORMAL.getCode(),1, 50));

        if (id != null && id > 0){
            model.addAttribute("byChannel", contentService.findChannel(id));
        }

        return PREFIX + "editChannelView";
    }

    @RequestMapping(value = "/submitChannel")
    public String addChannel(@RequestParam(value = "id",required = false) Integer id,
                             @RequestParam(value = "position_id",required = false) Integer position_id,
                             @RequestParam(value = "file",required = false) MultipartFile file,
                             @RequestParam(value = "name",required = false) String name,
                             @RequestParam(value = "descn",required = false) String descn,
                             @RequestParam(value = "sort",required = false) Integer sort,
                             @RequestParam(value = "status",required = false) Integer status,
                             @RequestParam(value = "parent_id",required = false) Integer parent_id,
                             Model model) {
        try{
            ByChannel byChannel = null;
            if (id != null && id > 0){
                byChannel = contentService.findChannel(id);
            }else{
                byChannel = new ByChannel();
            }
            byChannel.setPositionId(position_id);


            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byChannel.setImgUrl(img_url);
            }

            byChannel.setName(name);
            byChannel.setDescn(descn);
            byChannel.setStatus(status);
            byChannel.setSort(sort);
            byChannel.setCreateTime(new DateTime());
            byChannel.setUpdateTime(new DateTime());

            if (parent_id != null)
            {
                byChannel.setParentId(parent_id);
            }else {
                byChannel.setParentId(0);
            }

            contentService.insertChannel(byChannel);

//            PushRecord pushRecord = new PushRecord();
//            pushRecord.setName(name);
//            pushRecord.setTitle(title);
//            pushRecord.setContent(content);
//            pushRecord.setStatus(PushStatus.UNSEND.getCode());
//            pushRecord.setDescription(description);
//            pushRecord.setOperator(getCurrentUser().getId().toString());
//            pushRecord.setCreateTime(new DateTime());
//            pushRecord.setUpdateTime(new DateTime());
//            msgService.insertPushRecord(pushRecord);
//            //构建mongo查询条件
//            Map<String, Object> condition=new HashMap<String, Object>();
//            if (StringUtil.isNotBlank(login_name)) {
//                condition.put("login_name", login_name.trim());
//            }
//            if (StringUtil.isNotBlank(created_at)) {
//                condition.put("created_at", created_at.trim());
//            }
//            if (StringUtil.isNotBlank(province)&&StringUtil.isNotBlank(city)) {
//                city=city.endsWith("市")?city.substring(0,city.indexOf("市")):city;
//                String area=(province.trim()+" "+city.trim()).trim();
//                Pattern pattern = Pattern.compile("^.*" + area+ ".*$", Pattern.CASE_INSENSITIVE);
//                condition.put("area",pattern);
//            }
//            if (gender!=null) {
//                condition.put("gender", gender);
//            }
//
//
//            List<MemberInfo> memberInfos = mongoService.getMemberInfoList(condition);
//            for (int i = 0; i < memberInfos.size(); i++) {
//                MemberInfo memberInfo = memberInfos.get(i);
//
//                PushRecordDetail pushRecordDetail = new PushRecordDetail();
//                pushRecordDetail.setRecordId(pushRecord.getId());
//
//                pushRecordDetail.setUserid(memberInfo.getId());
//                pushRecordDetail.setChannelAvatar(memberInfo.getChannelAvatar());
//                pushRecordDetail.setChannelId(memberInfo.getChannelId().toString());
//                pushRecordDetail.setChannelUserId(memberInfo.getChannelUserId());
//
//                pushRecordDetail.setPushChannelId(memberInfo.getPushChannelId());
//                pushRecordDetail.setDeviceId(memberInfo.getDeviceId());
//                pushRecordDetail.setDeviceType(memberInfo.getDeviceType());
//                pushRecordDetail.setGender(memberInfo.getGender());
//                pushRecordDetail.setIsOta(memberInfo.getIsOta());
//                pushRecordDetail.setIsShell(memberInfo.getIsShell());
////                String loginNameEncoded=URLEncoder.encode(memberInfo.getLoginName(), "UTF-8");
//                System.out.println(i+" "+memberInfo.getLoginName());
//                pushRecordDetail.setLoginName(memberInfo.getLoginName());
//                pushRecordDetail.setLowerLoginName(memberInfo.getLowerLoginName());
//                pushRecordDetail.setPushType(memberInfo.getPushType());
//
//                pushRecordDetail.setStatus(PushStatus.UNSEND.getCode());
//                pushRecordDetail.setCreateTime(new DateTime());
//                pushRecordDetail.setUpdateTime(new DateTime());
//                try {
//                    msgService.insertPushRecordDetail(pushRecordDetail);
//                } catch (Exception e) {
//                    // TODO: handle exception
//                }
//            }
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "channelManage";
    }


    @RequestMapping(value = "/channelDetailView")
    public String channelDetailView(@RequestParam(value = "id") Integer id,
                                    @RequestParam(value = "position_id",required = false) Integer position_id,
                                    @RequestParam(value = "parent_id",required = false) Integer parent_id,
                                    Model model) {
        model.addAttribute("id", id);
        return PREFIX + "channelDetailView";
    }























    //Notice
    //Schedule
    @RequestMapping(value = "/addNoticeView")
    public String addNoticeView(@RequestParam(value = "id",required = false) Integer id,
                                  Model model) {

        model.addAttribute("noticeTypeList", NoticeType.getAllData());

        return PREFIX + "addNoticeView";
    }

    @RequestMapping(value = "/editNoticeView")
    public String editNoticeView(@RequestParam(value = "id",required = false) Integer id,
                                   Model model) {

        if (id != null && id > 0){
            model.addAttribute("notice", contentService.findNotice(id));
        }

        model.addAttribute("noticeTypeList", NoticeType.getAllData());

        return PREFIX + "editNoticeView";
    }

    @RequestMapping(value = "/submitNotice")
    public String submitNotice(@RequestParam(value = "id",required = false) Integer id,
                                 @RequestParam(value = "user_id",required = false) Integer user_id,
                                 @RequestParam(value = "file",required = false) MultipartFile file,
                                 @RequestParam(value = "name",required = false) String name,
                                 @RequestParam(value = "descn",required = false) String descn,
                                 @RequestParam(value = "sort",required = false) Integer sort,
                                 @RequestParam(value = "notice_type",required = false) Integer notice_type,
                                 @RequestParam(value = "status",required = false) Integer status,
                                 Model model) {
        try{
            ByNotice byNotice = null;
            if (id != null && id > 0){
                byNotice = contentService.findNotice(id);
            }else{
                byNotice = new ByNotice();
            }
            byNotice.setUserId(user_id);
            byNotice.setName(name);
            byNotice.setDescn(descn);
            byNotice.setStatus(status);
            byNotice.setSort(sort);
            byNotice.setNoticeType(notice_type);
            byNotice.setCreateTime(new DateTime());
            byNotice.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byNotice.setImgUrl(img_url);
            }

            contentService.insertNotice(byNotice);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "noticeManage";
    }

    @RequestMapping(value = "/noticeManage")
    public String noticeManage() {
        return PREFIX + "noticeManage";
    }

    @RequestMapping(value = "/getNoticeList")
    public void getNoticeList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                              @RequestParam(value = "user_id", required = false) Integer user_id,
                              @RequestParam(value = "notice_type",required = false) Integer notice_type,
                              Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

//        User user = getCurrentUser();
        List<ByNotice> list = contentService.selectNoticeListByPage(user_id, notice_type,(page-1)*pageSize, pageSize);
        int total = contentService.selectNoticeListCount(user_id, notice_type);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }


    //AD
    @RequestMapping(value = "/addAdView")
    public String addAdView(@RequestParam(value = "id",required = false) Integer id,
                                Model model) {

        model.addAttribute("adPositionTypeList", AdPositionType.getAllData());

        return PREFIX + "addAdView";
    }

    @RequestMapping(value = "/deleteAd")
    public String deleteAd(@RequestParam(value = "id",required = false) Integer id,
                           @RequestParam(value = "parent_id",required = false) Integer parent_id,
                            Model model) {

        if (id != null && id > 0){
            contentService.deleteAd(id);
        }

        if (parent_id != null && parent_id > 0){
            return PREFIX + "adDetailManage";
        }else{
            return PREFIX + "adManage";
        }
    }

    @RequestMapping(value = "/editAdView")
    public String editAdView(@RequestParam(value = "id",required = false) Integer id,
                                 Model model) {

        if (id != null && id > 0){
            model.addAttribute("ad", contentService.findAd(id));
        }

        model.addAttribute("adPositionTypeList", AdPositionType.getAllData());

        return PREFIX + "editAdView";
    }

    @RequestMapping(value = "/submitAd")
    public String submitAd(@RequestParam(value = "id",required = false) Integer id,
                               @RequestParam(value = "position_id",required = false) Integer position_id,
                               @RequestParam(value = "file",required = false) MultipartFile file,
                               @RequestParam(value = "name",required = false) String name,
                               @RequestParam(value = "subtitle",required = false) String subtitle,
                               @RequestParam(value = "descn",required = false) String descn,
                               @RequestParam(value = "sort",defaultValue = "1") Integer sort,
                               @RequestParam(value = "url",required = false) String url,
                               @RequestParam(value = "status",defaultValue = "1") Integer status,
                               Model model) {
        try{
            ByAd byAd = null;
            if (id != null && id > 0){
                byAd = contentService.findAd(id);
            }else{
                byAd = new ByAd();
            }
            byAd.setPositionId(position_id);
            byAd.setName(name);
            byAd.setSubtitle(subtitle);
            byAd.setDescn(descn);
            byAd.setStatus(status);
            byAd.setSort(sort);
            byAd.setUrl(url);
            byAd.setParentId(0);
            byAd.setCreateTime(new DateTime());
            byAd.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byAd.setImgUrl(img_url);
            }

            contentService.insertAd(byAd);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "adManage";
    }

    @RequestMapping(value = "/adManage")
    public String adManage(Model model) {
        model.addAttribute("adPositionTypeList", AdPositionType.getAllData());

        return PREFIX + "adManage";
    }

    @RequestMapping(value = "/getAdList")
    public void getAdList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                              @RequestParam(value = "position_id",required = false) Integer position_id,
                              Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByAd> list = contentService.selectAdListByPage(position_id, 0, BaseState.NORMAL.getCode(),(page-1)*pageSize, pageSize);
        int total = contentService.selectAdListCount(position_id, 0, BaseState.NORMAL.getCode());
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    //ad detail
    @RequestMapping(value = "/addAdDetailView")
    public String addAdDetailView(@RequestParam(value = "position_id",required = false) Integer position_id,
                                  @RequestParam(value = "parent_id",required = false) Integer parent_id,
                            Model model) {

        model.addAttribute("position_id", position_id);
        model.addAttribute("parent_id", parent_id);
        model.addAttribute("adPositionTypeList", AdPositionType.getAllData());

        if (position_id == AdPositionType.INDEX_CEHUA.getCode()
                || position_id == AdPositionType.INDEX_ZHUCHI.getCode()
                || position_id == AdPositionType.INDEX_SHEYINGSHI.getCode()
                || position_id == AdPositionType.INDEX_HUAZHUANGSHI.getCode()
                || position_id == AdPositionType.INDEX_SHEXIANGSHI.getCode() ){
            model.addAttribute("is_show", true);
        }

        return PREFIX + "addAdDetailView";
    }

    @RequestMapping(value = "/editAdDetailView")
    public String editAdDetailView(@RequestParam(value = "id",required = false) Integer id,
                                   @RequestParam(value = "position_id",required = false) Integer position_id,
                                   @RequestParam(value = "parent_id",required = false) Integer parent_id,
                             Model model) {

        if (id != null && id > 0){
            model.addAttribute("ad", contentService.findAd(id));
        }

        model.addAttribute("position_id", position_id);
        model.addAttribute("parent_id", parent_id);
        model.addAttribute("adPositionTypeList", AdPositionType.getAllData());

        if (position_id == AdPositionType.INDEX_CEHUA.getCode()
                || position_id == AdPositionType.INDEX_ZHUCHI.getCode()
                || position_id == AdPositionType.INDEX_SHEYINGSHI.getCode()
                || position_id == AdPositionType.INDEX_HUAZHUANGSHI.getCode()
                || position_id == AdPositionType.INDEX_SHEXIANGSHI.getCode() ){
            model.addAttribute("is_show", true);
        }

        return PREFIX + "editAdDetailView";
    }

    @RequestMapping(value = "/submitAdDetail")
    public String submitAd(@RequestParam(value = "id",required = false) Integer id,
                           @RequestParam(value = "position_id",required = false) Integer position_id,
                           @RequestParam(value = "file",required = false) MultipartFile file,
                           @RequestParam(value = "name",required = false) String name,
                           @RequestParam(value = "subtitle",required = false) String subtitle,
                           @RequestParam(value = "parent_id",required = false) Integer parent_id,
                           @RequestParam(value = "entity_id",required = false) Integer entity_id,
                           @RequestParam(value = "descn",required = false) String descn,
                           @RequestParam(value = "sort",defaultValue = "1") Integer sort,
                           @RequestParam(value = "url",required = false) String url,
                           @RequestParam(value = "status",defaultValue = "1") Integer status,
                           Model model) {
        try{
            ByAd byAd = null;
            if (id != null && id > 0){
                byAd = contentService.findAd(id);
            }else{
                byAd = new ByAd();
            }
            byAd.setPositionId(position_id);
            byAd.setName(name);
            byAd.setSubtitle(subtitle);
            byAd.setDescn(descn);
            byAd.setStatus(status);
            if (sort == null){
                sort = 1;
            }
            byAd.setSort(sort);
            byAd.setUrl(url);
            byAd.setParentId(parent_id);
            byAd.setEntityId(entity_id);
            byAd.setCreateTime(new DateTime());
            byAd.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byAd.setImgUrl(img_url);
            }

            contentService.insertAd(byAd);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }

//        model.addAttribute("position_id", position_id);
//        model.addAttribute("parent_id", parent_id);
        return "redirect:"+PREFIX + "adDetailManage?position_id="+position_id+"&parent_id="+parent_id;
    }

    @RequestMapping(value = "/adDetailManage")
    public String adDetailManage(@RequestParam(value = "position_id",required = false) Integer position_id,
                                 @RequestParam(value = "parent_id",required = false) Integer parent_id,
                                 Model model) {

        model.addAttribute("position_id", position_id);
        model.addAttribute("parent_id", parent_id);

        return PREFIX + "adDetailManage";
    }

    @RequestMapping(value = "/getAdDetailList")
    public void getAdDetailList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                          @RequestParam(value = "position_id",required = false) Integer position_id,
                          @RequestParam(value = "parent_id",required = false) Integer parent_id,
                          Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByAd> list = contentService.selectAdListByPage(position_id, parent_id, null,(page-1)*pageSize, pageSize);
        int total = contentService.selectAdListCount(position_id, parent_id, null);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    //Article
    @RequestMapping(value = "/addArticleView")
    public String addArticleView(@RequestParam(value = "id",required = false) Integer id,
                            Model model) {
        model.addAttribute("articleTypeList", ArticleType.getAllData());
        model.addAttribute("articlePositionTypeList", ArticlePositionType.getAllData());

        return PREFIX + "addArticleView";
    }

    @RequestMapping(value = "/editArticleView")
    public String editArticleView(@RequestParam(value = "id",required = false) Integer id,
                             Model model) {

        if (id != null && id > 0){
            model.addAttribute("article", contentService.findArticle(id));
        }

        model.addAttribute("articleTypeList", ArticleType.getAllData());
        model.addAttribute("articlePositionTypeList", ArticlePositionType.getAllData());

        return PREFIX + "editArticleView";
    }

    @RequestMapping(value = "/submitArticle")
    public String submitArticle(@RequestParam(value = "id",required = false) Integer id,
                           @RequestParam(value = "user_id",required = false) Integer user_id,
                           @RequestParam(value = "position_id",required = false) Integer position_id,
                           @RequestParam(value = "article_type",required = false) Integer article_type,
                           @RequestParam(value = "file",required = false) MultipartFile file,
                           @RequestParam(value = "name",required = false) String name,
                           @RequestParam(value = "descn",required = false) String descn,
                           @RequestParam(value = "status",defaultValue = "1") Integer status,
                           Model model) {
        try{
            ByArticle byArticle = null;
            if (id != null && id > 0){
                byArticle = contentService.findArticle(id);
            }else{
                byArticle = new ByArticle();
            }
            byArticle.setUserId(user_id);
            byArticle.setPositionId(position_id);
            byArticle.setArticleType(article_type);
            byArticle.setName(name);
            byArticle.setDescn(descn);
            byArticle.setStatus(status);
            byArticle.setCreateTime(new DateTime());
            byArticle.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byArticle.setImgUrl(img_url);
            }

            contentService.insertArticle(byArticle);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "articleManage";
    }

    @RequestMapping(value = "/articleManage")
    public String articleManage() {
        return PREFIX + "articleManage";
    }

    @RequestMapping(value = "/getArticleList")
    public void getArticleList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                              @RequestParam(value = "user_id", required = false) Integer user_id,
                               @RequestParam(value = "position_id", required = false) Integer position_id,
                               @RequestParam(value = "article_type", required = false) Integer article_type,
                              Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

//        User user = getCurrentUser();
        List<ByArticle> list = contentService.selectArticleListByPage(user_id, position_id, article_type,(page-1)*pageSize, pageSize);
        int total = contentService.selectArticleListCount(user_id, position_id, article_type);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    //评论列表
    @RequestMapping(value = "/commentManage")
    public String commentManage() {
        return PREFIX + "commentManage";
    }

    @RequestMapping(value = "/getCommentList")
    public void getCommentList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                               @RequestParam(value = "user_id", required = false) Integer user_id,
                               @RequestParam(value = "table_name",required = false) String table_name,
                               @RequestParam(value = "table_id",required = false) String table_id,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

//        User user = getCurrentUser();
        List<ByUserComment> list = contentService.selectCommentListByPage(user_id, table_name, table_id,(page-1)*pageSize, pageSize);
        int total = contentService.selectCommentListCount(user_id, table_name, table_id);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    //我的评论
    @RequestMapping(value = "/myComment")
    public String myComment() {
        return PREFIX + "myComment";
    }

    @RequestMapping(value = "/getMyCommentList")
    public void getMyCommentList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                 @RequestParam(value = "table_name", required = false) String table_name,
                                 @RequestParam(value = "table_id", required = false) String table_id,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserComment> list = contentService.selectCommentListByPage(user.getId(), table_name, table_id,(page-1)*pageSize, pageSize);
        int total = contentService.selectCommentListCount(user.getId(), table_name, table_id);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }


    //关键字
    @RequestMapping(value = "/keyWordManage")
    public String keyWordManage(Model model) {
        model.addAttribute("positionList", ChannelType.getAllChannel());
        model.addAttribute("parentList", contentService.selectChannelListByPage(null, 0, BaseState.NORMAL.getCode(),1, 50));

        return PREFIX + "keyWordManage";
    }

    @RequestMapping(value = "/getKeyWordList")
    public void getKeyWordList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                               @RequestParam(value = "status", required = false) Integer status,
                               @RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "position_id", required = false) Integer position_id,
                               @RequestParam(value = "parent_id", required = false) Integer parent_id,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();

        List<ByChannelKeyWordBvo> list = new ArrayList<ByChannelKeyWordBvo>();
        List<ByChannelKeyword> byChannelKeywords = contentService.selectKeyWordListByPage(position_id, parent_id, name, status,(page-1)*pageSize, pageSize);

        if (byChannelKeywords != null && byChannelKeywords.size() > 0){
            for (ByChannelKeyword current : byChannelKeywords){
                ByChannelKeyWordBvo byChannelKeyWordBvo = ByChannelKeyWordBvo.copyFrom(current, contentService.findChannel(current.getParentId()));
                list.add(byChannelKeyWordBvo);
            }
        }

        int total = contentService.selectKeyWordListCount(position_id, parent_id, name, status);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }
    @RequestMapping(value = "/addKeyWordView")
    public String addKeyWordView(@RequestParam(value = "id",required = false) Integer id,
                                 Model model) {
        model.addAttribute("positionList", ChannelType.getAllChannel());
        model.addAttribute("parentList", contentService.selectChannelListByPage(null, 0, BaseState.NORMAL.getCode(),1, 50));

        return PREFIX + "addKeyWordView";
    }

    @RequestMapping(value = "/editKeyWordView")
    public String editKeyWordView(@RequestParam(value = "id",required = false) Integer id,
                                  Model model) {
        model.addAttribute("positionList", ChannelType.getAllChannel());
        model.addAttribute("parentList", contentService.selectChannelListByPage(null, 0, BaseState.NORMAL.getCode(),1, 50));

        if (id != null && id > 0){
            model.addAttribute("byChannelKeyWord", contentService.findKeyWord(id));
        }

        return PREFIX + "editKeyWordView";
    }

    @RequestMapping(value = "/submitKeyWord")
    public String submitKeyWord(@RequestParam(value = "id",required = false) Integer id,
                             @RequestParam(value = "position_id",required = false) Integer position_id,
                             @RequestParam(value = "parent_id",required = false) Integer parent_id,
                             @RequestParam(value = "name",required = false) String name,
                             @RequestParam(value = "descn",required = false) String descn,
                             @RequestParam(value = "sort",required = false) Integer sort,
                             @RequestParam(value = "status",required = false) Integer status,
                             @RequestParam(value = "url",required = false) String url,
                             Model model) {
        try{
            ByChannelKeyword byChannelKeyword = null;
            if (id != null && id > 0){
                byChannelKeyword = contentService.findKeyWord(id);
            }else{
                byChannelKeyword = new ByChannelKeyword();
            }

            byChannelKeyword.setPositionId(position_id);
            byChannelKeyword.setName(name);
            byChannelKeyword.setDescn(descn);
            byChannelKeyword.setStatus(status);
            byChannelKeyword.setSort(sort);
            byChannelKeyword.setUrl(url);
            byChannelKeyword.setCreateTime(new DateTime());
            byChannelKeyword.setUpdateTime(new DateTime());

            if (parent_id != null)
            {
                byChannelKeyword.setParentId(parent_id);
            }else {
                byChannelKeyword.setParentId(0);
            }

            contentService.insertKeyWord(byChannelKeyword);

            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return PREFIX + "keyWordManage";
    }


    @RequestMapping(value = "/changeKeyWordStatus")
    public void changeKeyWordStatus(@RequestParam(value = "id") Integer id,
                                    @RequestParam(value = "status",required = false) Integer status,
                                    Model model) {
        model.addAttribute("id", id);

        if (id != null && id > 0){
            ByChannelKeyword byChannelKeyword = contentService.findKeyWord(id);
            byChannelKeyword.setStatus(status);
            contentService.insertKeyWord(byChannelKeyword);

            model.addAttribute("msg", SUCCESS);
            return;
        }

        model.addAttribute("msg", FAIL);
        return;
    }
}
